package com.ipzoe.app.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.ipzoe.app.dto.BannerResponseDTO;
import com.ipzoe.cms.domain.Banner;
import com.ipzoe.cms.enums.BannerTypeEnum;
import com.ipzoe.cms.service.IBannerService;
import com.ipzoe.common.core.controller.BaseController;
import com.ipzoe.common.core.domain.AjaxResult;
import com.ipzoe.common.core.page.TableDataInfo;
import com.ipzoe.common.exception.CustomException;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/v1/banner")
@Validated
@Api(tags = "banner相关")
@Slf4j
public class BannerController extends BaseController {

    @Autowired
    private IBannerService iBannerService;

    /**
     * 查询banner
     */
    @PostMapping("/list/{location}")
    @ApiOperation("根据位置查询banner")
    public AjaxResult list(@PathVariable String location)
    {
        LambdaQueryWrapper<Banner> bannerLqw = new LambdaQueryWrapper<>();
        bannerLqw.eq(Banner::getUseFlag, 1)
                .eq(Banner::getLocation, location)
                .orderByAsc(Banner::getOrderNum);
        List<Banner> list = iBannerService.list(bannerLqw);

        //如果存在视频类的就取最新的一个视频
        List<Banner> resultList = Lists.newArrayList();
        if(CollUtil.isNotEmpty(list)){
            Map<Integer, List<Banner>> groupByTypeMap = list.parallelStream().collect(Collectors.groupingBy(Banner::getBannerType));
            if(CollUtil.isNotEmpty(groupByTypeMap.get(BannerTypeEnum.VIDEO.getCode()))){
                List<Banner> sortedVideoBannerList = groupByTypeMap.get(BannerTypeEnum.VIDEO.getCode()).parallelStream().sorted(Comparator.comparing(Banner::getId).reversed()).collect(Collectors.toList());
                resultList.add(sortedVideoBannerList.get(0));
            }else{
                resultList.addAll(groupByTypeMap.get(BannerTypeEnum.PIC.getCode()));
            }
        }
        return AjaxResult.success(list);
    }

}
